export function pickPostion(viewer = window.viewer) {
    const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    return new Promise(res => {
        handler.setInputAction((event) => {
            handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
            viewer.scene.globe.depthTestAgainstTerrain = true;
            const feature = viewer.scene.pick(event.position)
            if(feature){
                const position = viewer.scene.pickPosition(event.position)
                const lngLatPoint = getLngLat(position)
                res({position, lngLatPoint})
            }else{
                viewer.scene.globe.depthTestAgainstTerrain = false;
                const position  = viewer.camera.pickEllipsoid(event.position,viewer.scene.globe.ellipsoid);
                const lngLatPoint = getLngLat(position)
                res({position, lngLatPoint})
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    })
}

function getLngLat (position) {
    const {
        longitude,
        latitude,
        height
    } = Cesium.Cartographic.fromCartesian(position)
    const lng = Cesium.Math.toDegrees(longitude)
    const lat = Cesium.Math.toDegrees(latitude)
    return [lng, lat, height]
}